package com.zx.article.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/AuthCodeServlet")
public class AuthCodeServlet extends HttpServlet {

	private static final long serialVersionUID = -4218896228960215439L;
	private static char[] chs = "1234567890".toCharArray();

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		BufferedImage image = new BufferedImage(75, 25, BufferedImage.TYPE_INT_RGB);
		Graphics2D g = image.createGraphics();
		g.setColor(new Color(200, 200, 255));
		g.fillRect(0, 0, 75, 25);
		g.setFont(new Font("隶书", Font.BOLD, 15));
		StringBuffer str = new StringBuffer();
		Random r = new Random();
		for (int i = 0; i < 4; i++) {
			int index = r.nextInt(chs.length);
			g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
			g.drawString(chs[index] + "", 15 * i + 3, 16 + r.nextInt(3));
			str.append(chs[index]);
		}
		request.getSession().setAttribute("authcode", str.toString());
		ImageIO.write(image, "jpg", response.getOutputStream());
	}

}
